package com.os.controller;

import com.os.dao.PersonRepository;
import com.os.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class DataController {

    //spring jpa已自动注册bean，所以可自动注入
    @Autowired
    private PersonRepository personRepository;

    /**
     * 保存，save支持批量保存
     * 删除，支持id删除对象、批量删除以及删除全部
     * void delete(ID id);
     * void delete(T entity);
     * void delete(Interable<? extends T> entities);
     * void deleteAll();
     */
    @RequestMapping("/save")
    public Person save(String name, String address, Integer age){
        Person p = personRepository.save(new Person(null, name, age, address));

        return p;
    }

    /**
     * 测试findByAddress
     */
    @RequestMapping("/q1")
    public List<Person> q1(String address){
        List<Person> personList = personRepository.findByAddress(address);

        return personList;
    }

    /**
     * 测试finaByNameAndAddress
     */
    @RequestMapping("/q2")
    public Person q2(String name, String address){
        Person person = personRepository.findByNameAndAddress(name, address);

        return person;
    }

    /**
     * 测试withNameAndAddressQuery
     */
    @RequestMapping("/q3")
    public Person q3(String name, String address){
        Person person = personRepository.withNameAndAddressQuery(name, address);

        return person;
    }

    /**
     * 测试withNameAndAddressNamedQuery
     */
    @RequestMapping("/q4")
    public Person q4(String name, String address){
        Person person = personRepository.withNameAndAddressNamedQuery(name, address);

        return person;
    }

    /**
     * 测试排序
     */
    @RequestMapping("/sort")
    public List<Person> sort(){
        List<Person> personList = personRepository.findAll(Sort.by("age"));

        return personList;
    }

    /**
     * 测试分页
     */
    @RequestMapping("/page")
    public Page<Person> page(){
        Page<Person> personPage = personRepository.findAll(PageRequest.of(1, 2));

        return personPage;
    }
}
